//@dart=2.12
import 'dart:convert';

import 'package:base_flutter/base_flutter.dart';
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:ls_work/bad_event/bad_event_ext.dart';
import 'package:ls_work/login/page/user_manager.dart';
import 'package:ls_work/res/colors.dart';
import 'package:ls_work/ui/select_old_page.dart';
import 'package:ls_work/widgets/event_input_widget.dart';
import 'package:saas_order_meal/model/combo_model.dart';
import 'package:saas_order_meal/net/net_response/code_value_list.dart';

import '../bad_event_model.dart';
import '../response/event_detail_data.dart';
import '../response/event_equipment_list_data.dart';
import '../ui/choose_service_group_page.dart';

class CreateBadEventViewModel extends BaseViewModel {
  List<EventEquipmentListData> equipmentList = [];
  dynamic eventId;

  CreateBadEventViewModel(BuildContext? context, {dynamic eventType,this.eventId})
      : super(context) {
    this.eventDetail =
        EventDetailData(qualityAnomalousEvent: QualityAnomalousEvent());
    if (eventType != null) {
      eventDetail?.eventType = eventType;
    }
  }

  var model = BadEventModel();
  EventDetailData? eventDetail;

  var commonModel = ComboModel();

  Map<String, List<CodeValueList>> comboListMap = {};

  Future<void> initData() async {
    showLoadingState();
    try {
      await getComboData('400004');
      await getComboData('97');
      await getComboData('96');
      await getComboData('44263');
      await getComboData('5878');
      await getComboData('4319');
      await getComboData('400006');
      await getComboData('400007');
      await getComboData('59');
      await getEquipmentList();

      if(eventId!=null){
        eventDetail = await model.eventDetail(id: eventId);
      }
      showContent();
    } catch (e) {
      showErrorState(e.toNetError());
    }
  }

  Future<void> getComboData(String code) async {
    comboListMap[code] = await commonModel.getComboData(code);
  }

  Future<void> getEquipmentList() async {
    equipmentList = await model.eventEquipment();
  }

  @override
  void onCreated() {
    super.onCreated();
    initData();
  }

  void chooseElder() {
    Go().push(SelectOldPage((old) {
      Go().pop();
      eventDetail?.customerName = old.name;
      eventDetail?.customerId = old.id;
      eventDetail?.bedNo = old.bedNo;
      eventDetail?.sexName = old.sexName;
      eventDetail?.age = old.age;
      eventDetail?.sex = old.sex;
      eventDetail?.checkinDate = old.intoDate;
      eventDetail?.nurseLevel = old.nurseLevelId;
      eventDetail?.nurseLevelName = old.nurseLevelName;

      eventDetail?.qualityAnomalousEvent?.customerName = old.name;
      eventDetail?.qualityAnomalousEvent?.bedNo = old.bedNo;
      eventDetail?.qualityAnomalousEvent?.sexName = old.sexName;
      eventDetail?.qualityAnomalousEvent?.sex = old.sex;
      notifyListeners();
    }));
  }

  void chooseOccurrenceTime() {
    var nowTime = eventDetail?.occurrenceTime?.toDate();
    var format = [yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ":", ss];
    DatePicker.showDateTimePicker(context, currentTime: nowTime,
        onConfirm: (date) {
      eventDetail?.occurrenceTime = date!.toDateStr(format);
      notifyListeners();
    });
  }

  void chooseConsciousState() {
    PickerDataWithIdModel? data;
    if (!(eventDetail?.qualityAnomalousEvent?.consciousState ?? "")
        .isNullOrEmpty()) {
      data = PickerDataWithIdModel(
          pickName: eventDetail?.qualityAnomalousEvent?.consciousState,
          pickId: eventDetail?.qualityAnomalousEvent?.consciousState);
    }
    var list = [
      PickerDataWithIdModel(pickName: '清醒', pickId: '清醒'),
      PickerDataWithIdModel(pickName: '嗜睡', pickId: '嗜睡'),
      PickerDataWithIdModel(pickName: '混乱', pickId: '混乱'),
      PickerDataWithIdModel(pickName: '昏迷', pickId: '昏迷'),
    ];
    DataPickerView(context, list, currentFirstData: data,
        onSubmitListener: (p1, p2, p3) {
      var item = list[p1];
      eventDetail?.qualityAnomalousEvent?.consciousState = item.pickId;
      notifyListeners();
    }).show();
    ;
  }

  void chooseYesOrNo(num? nowValue, Function(num value) listener,
      {bool isHave = false}) {
    var items = isHave
        ? [
            PickerDataWithIdModel(pickId: '1', pickName: '有'),
            PickerDataWithIdModel(pickId: '0', pickName: '无'),
          ]
        : [
            PickerDataWithIdModel(pickId: '1', pickName: '是'),
            PickerDataWithIdModel(pickId: '0', pickName: '否'),
          ];

    var current = nowValue == null
        ? null
        : items.firstWhere((element) => num.parse(element.pickId!) == nowValue);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      var value = num.parse(item.pickId!);
      listener(value);
    }).show();
  }

  void chooseActivityAnalyze() {
    ///1-自由活动 2-卧床,3-轮椅,4-使用助行器/拐杖,5-可由人员扶持走动 6-受约束
    var items = [
      PickerDataWithIdModel(pickId: '1', pickName: '自由活动'),
      PickerDataWithIdModel(pickId: '2', pickName: '卧床'),
      PickerDataWithIdModel(pickId: '3', pickName: '轮椅'),
      PickerDataWithIdModel(pickId: '4', pickName: '使用助行器/拐杖'),
      PickerDataWithIdModel(pickId: '5', pickName: '可由人员扶持走动'),
      PickerDataWithIdModel(pickId: '6', pickName: '受约束'),
    ];
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return MultiChooseSheet(
            list: items,
            title: '长者活动性',
            submitClick: (ids) {
              eventDetail?.qualityAnomalousEvent?.activityAnalyze = ids;
              notifyListeners();
            },
            chooseIds:
                eventDetail?.qualityAnomalousEvent?.activityAnalyze ?? "",
          );
        },
        backgroundColor: Colors.transparent);
  }

  void chooseLocation() {
    ///0-床旁,卧室，1-卫生间，2-浴室，3-轮椅，4-活动区，5-其他
    var items = [
      PickerDataWithIdModel(pickName: '床旁,卧室', pickId: '0'),
      PickerDataWithIdModel(pickName: '卫生间', pickId: '1'),
      PickerDataWithIdModel(pickName: '浴室', pickId: '2'),
      PickerDataWithIdModel(pickName: '轮椅', pickId: '3'),
      PickerDataWithIdModel(pickName: '活动区', pickId: '4'),
      PickerDataWithIdModel(pickName: '其他', pickId: '5'),
    ];

    var current =
        eventDetail?.qualityAnomalousEvent?.falldownLocationType == null
            ? null
            : items.firstWhere((element) =>
                num.parse(element.pickId!) ==
                eventDetail?.qualityAnomalousEvent?.falldownLocationType);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      eventDetail?.qualityAnomalousEvent?.falldownLocationType =
          num.parse(item.pickId!);
      notifyListeners();
    }).show();
  }

  void chooseMedicineLocation() {
    ///0-床旁,卧室，1-卫生间，2-浴室，3-轮椅，4-活动区，5-其他
    var items = [
      PickerDataWithIdModel(pickName: '床旁,卧室', pickId: '0'),
      PickerDataWithIdModel(pickName: '卫生间', pickId: '1'),
      PickerDataWithIdModel(pickName: '浴室', pickId: '2'),
      PickerDataWithIdModel(pickName: '轮椅', pickId: '3'),
      PickerDataWithIdModel(pickName: '活动区', pickId: '4'),
      PickerDataWithIdModel(pickName: '其他', pickId: '5'),
    ];

    var current =
    eventDetail?.qualityAnomalousEvent?.occurLocationType == null
        ? null
        : items.firstWhere((element) =>
    num.parse(element.pickId!) ==
        eventDetail?.qualityAnomalousEvent?.occurLocationType);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
          var item = items[p1];
          eventDetail?.qualityAnomalousEvent?.occurLocationType =
              num.parse(item.pickId!);
          notifyListeners();
        }).show();
  }

  void chooseComboInfo(
      {required String code,
      String? currentValue,
      double itemExtent = 40,
      required Function(CodeValueList value) onApply}) {
    var list = comboListMap[code] ?? [];
    var currentItem = currentValue == null
        ? null
        : list.firstWhere((element) => element.codeValue == currentValue);
    DataPickerView(context, list, currentFirstData: currentItem,
            onSubmitListener: (p1, p2, p3) {
      var item = list[p1];
      onApply(item);
    }, itemExtent: itemExtent)
        .show();
  }

  void chooseBedrailUsage() {
    ///0未使用 1仅单侧或部分使用床栏 2双侧使用
    var items = [
      PickerDataWithIdModel(pickId: '0', pickName: '未使用'),
      PickerDataWithIdModel(pickId: '1', pickName: '仅单侧或部分使用床栏'),
      PickerDataWithIdModel(pickId: '2', pickName: '双侧使用'),
    ];
    var useage = eventDetail?.qualityAnomalousEvent?.bedrailUsage;
    var currentData = useage == null
        ? null
        : items
            .firstWhere((element) => useage == num.tryParse(element.pickId!));
    DataPickerView(context, items, currentFirstData: currentData,
        onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      eventDetail?.qualityAnomalousEvent?.bedrailUsage =
          num.tryParse(item.pickId!);
      notifyListeners();
    }).show();
  }

  void chooseEquipment() {
    var currentEquipment =
        eventDetail?.qualityAnomalousEvent?.accessories == null
            ? null
            : equipmentList.firstWhere((element) =>
                element.id == eventDetail?.qualityAnomalousEvent?.accessories);
    DataPickerView(context, equipmentList, currentFirstData: currentEquipment,
        onSubmitListener: (p1, p2, p3) {
      var item = equipmentList[p1];
      eventDetail?.qualityAnomalousEvent?.accessories = item.id;
      notifyListeners();
    }).show();
  }

  void chooseTime(String? valueTime, Function(String dateTime) onApply,
      {List<String> format = const [
        'yyyy',
        '-',
        'mm',
        '-',
        'dd',
        ' ',
        'HH',
        ':',
        'nn',
        ':',
        'ss'
      ]}) {
    var curent = valueTime?.toDate();
    DatePicker.showDateTimePicker(context, currentTime: curent,
        onConfirm: (date) {
      onApply(date!.toDateStr(format));
    });
  }

  void chooseDate(String? valueTime, Function(String dateTime) onApply,
      {List<String> format = const [
        'yyyy',
        '-',
        'mm',
        '-',
        'dd',
      ]}) {
    var curent = valueTime?.toDate();
    DatePicker.showDatePicker(context, currentTime: curent, onConfirm: (date) {
      onApply(date!.toDateStr(format));

    });
  }

  void chooseMedicineHours() {
    ///0表示： 1小时内 1表示： 1-2小时， 2表示：2-3小时
    var items = [
      PickerDataWithIdModel(pickId: '0', pickName: '1小时内'),
      PickerDataWithIdModel(pickId: '1', pickName: '1-2小时'),
      PickerDataWithIdModel(pickId: '2', pickName: '2-3小时'),
    ];
    var hour = eventDetail?.qualityAnomalousEvent?.medicineHours;
    var current = hour == null
        ? null
        : items.firstWhere((e) => num.tryParse(e.pickId!) == hour);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
      var item = items[p1];
      eventDetail?.qualityAnomalousEvent?.medicineHours =
          num.tryParse(item.pickId!);
      notifyListeners();
    }).show();
  }

  Future<void> submitSave() async {

    if(eventDetail?.customerId==null){
      showToast("请选择长者");
      return;
    }

    if(eventDetail?.occurrenceTime.isNullOrEmpty()==true){
      showToast("请选择发生时间");
      return;
    }

    if(eventDetail?.eventType==1){
      if(eventDetail?.qualityAnomalousEvent?.consciousState.isNullOrEmpty()==true){
        showToast("请选择事发时意识状态");
        return;
      }
      if(eventDetail?.qualityAnomalousEvent?.falldownLocationType==null){
        showToast("请选择发生地点");
        return;
      }
      if(eventDetail?.qualityAnomalousEvent?.eventDescription.isNullOrEmpty()==true){
        showToast("请输入事件说明");
        return;
      }
      if(eventDetail?.qualityAnomalousEvent?.processDescription.isNullOrEmpty()==true){
        showToast("请输入处理情形");
        return;
      }
    }

    eventDetail?.qualityAnomalousEvent?.reportTime = DateTime.now()
        .toDateStr([yyyy, '-', mm, '-', dd, ' ', HH, ':', nn, ":", ss]);
    eventDetail?.qualityAnomalousEvent?.reporterName = UserManager.userName;

    var submitMap = eventDetail?.toSubmitJson();
    submitMap!["jsonStr"] = jsonEncode(submitMap);
    submitMap.removeWhere((key, value) => value == null);
    showLoadingDialog(msg: '提交中...');
    try {
      if(eventId!=null){
        await model.updateEvent(submitMap,eventDetail?.eventType);
      }else{
        await model.createBadEvent(submitMap,eventDetail?.eventType);
      }
      if(eventDetail?.qualityAnomalousEvent?.generateShiftInformation==1){
        await createHandOver();
      }
      hideDialog();
      showToast('提交成功');
      finish(data: true);
    } catch (e) {
      print(e);
      hideDialog();
      showToast(e.toNetError());
    }
  }

  Future<void> chooseNotify() async {
    List<dynamic>? notifyList = await Go().push(ChooseServiceGroupPage(
      chooseList: eventDetail?.qualityAnomalousEvent?.messageMan ?? [],
    ));
    if (notifyList != null) {
      eventDetail?.qualityAnomalousEvent?.messageMan = notifyList;
      notifyListeners();
    }
  }

  Future<void> createHandOver() async {
    var map = <String, dynamic>{
      "sourceType": 7,
      "customerElderId": eventDetail?.customerId
    };
    if (eventDetail?.eventType == 1) {
      var event = eventDetail?.qualityAnomalousEvent;
      map['eventExplain'] =
          "发生时间:${eventDetail?.qualityAnomalousEvent?.reportTime}\n长者姓名:${eventDetail?.customerName}\n事发时意识状态:${event?.consciousState}\n入住时跌倒危险群:${event?.falldownHighRishName} 1\n长者活动性: ${event?.activityAnalyze?.activityAnalyzeName}\n诊断:${event?.diagnose}\n发生地点:${event?.falldownLocationType?.locationName}\n跌倒描述人:${event?.qualityBy?.comboDataName((comboListMap['400004'] ?? []))}\n发现人:${event?.foundName}\n发现人身份:${event?.foundPosts}\n长辈情况备注:${event?.circumstanceRemark}\n本次跌倒事件为本次入住中第${event?.falldownTimes}次跌倒\n事件说明:${event?.eventDescription}\n处理情形:${event?.processDescription}\n跌倒时有无陪伴:${event?.fallAccompany.haveOrNot}\n跌倒外在因素:${event?.fallFactor?.comboDataName((comboListMap['400006'] ?? []))}\n发生于下列何种活动中: ${event?.occurrenceActivityType?.comboDataName((comboListMap['97'] ?? []))}\n下床（或移动）动机为何:${event?.motivationType?.comboDataName((comboListMap['96'] ?? []))}\n事件发生时是否已使用床栏的保护:${event?.bedrailUsage?.bedrailUsageName}\n跌倒前是否事先建立【高危险性上-跌倒】的护理计划:${event?.antiFalldownPlan.yesOrNo}\n事件发生前是否给予【预防跌倒】宣教活说明:${event?.preventiveAction.yesOrNo}\n跌倒事件发生前24小时内，使用药物:${event?.medicineInfo}\n跌倒前体位:${event?.bodyPositionBeforeFallingType?.comboDataName((comboListMap['44263'] ?? []))}\n辅具/环境:${event?.accessoriesOrEnvironmentType?.comboDataName((comboListMap['5878'] ?? []))}\n跌倒前的约束状态:${event?.constraintStatusBeforeFalling.yesOrNo}\n穿鞋情况:${event?.wearingShoesSituationType?.comboDataName((comboListMap['4319'] ?? []))}\n辅具:${event?.accessories?.equipmentName(equipmentList)}\n视力辅具:${event?.visionAccessories.yesOrNo}\n助听器:${event?.hearingAids.yesOrNo}\n告知家属:${event?.informFamilies.yesOrNo}\n已通知医生:${event?.informDoctor.yesOrNo}\n已通知护士:${event?.informNurse.yesOrNo}\n打急救电话:${event?.callEmergencyNumber.yesOrNo}\n通知人:${(event?.messageMan ?? []).map((e) => e['name']).join(",")}\n通知医生时间:${event?.doctorDate ?? ""}\n通知护士时间:${event?.nurseDate ?? ""}\n通知家属:${event?.dependentsDate ?? ""}\n48H内是否送医:${event?.evacuateHospital.yesOrNo}\n48H内是否去世:${event?.passAway.yesOrNo}\n入住时跌倒高危险群筛选正确:${event?.falldownScreenCorrectness == 1 ? '是' : event?.falldownScreenCorrectness == 0 ? '其他' : ''} ${event?.screenIncorrectItem ??""}\n跌倒造成的伤害:${event?.damageLevelName ?? ""}\n有无造成损伤:${event?.damage.haveOrNot}\n跌倒发生时长者的受伤部位:${event?.damageParts?.split(",").map((e) => e.damagePartsName).join(",")}\n损伤的具体描述（部位、意识程度等）:${event?.damageDescription??""}\n造成跌倒的原因:${event?.healthReason}\n查体:\n腋温（°C）:${event?.armpitTemperature}°C\n血压（mmHg):${event?.bloodPressure}mmHg\n脉搏（次/分）:${event?.pulse}次/分\n血糖(mmol/L):${event?.bloodSugar}mmol/L\n呼吸（次/分）:${event?.breathe}次/分\n疼痛评估（VAS）:${event?.painVas}\n血氧饱和度（%）:${event?.bloodOxygen}%\n疼痛评估（Algoplus）:${event?.painAlg}\n四肢活动是否异常:${event?.limbs.yesOrNo}\n是否使用抗凝剂:${event?.anticoagulant.yesOrNo}\n临床检查及初步诊断:${event?.diagnosis}\n抗凝剂药品名:${event?.anticoagulantName}\n是否与药源因素相关:${event?.medicinalSource.yesOrNo}\n药源性因素的药品:${event?.medicinalSourceName}\n措施（现场+多学科讨论）:${event?.measure??""}\n是否修改护理计划:${event?.nurseType.yesOrNo} 修改于${event?.nurseTypeDate}\n是否修改个人计划:${event?.single.yesOrNo} 修改于${event?.singleDate}\n";
    }

    await model.createHandOver(map);
  }

  void chooseFindStaff() {
    var items = [
      PickerDataWithIdModel(pickId: '0',pickName: '跌倒长者家属'),
      PickerDataWithIdModel(pickId: '1',pickName: '护士'),
      PickerDataWithIdModel(pickId: '2',pickName: '介护士'),
      PickerDataWithIdModel(pickId: '3',pickName: '其他'),
    ];

    var current =
    eventDetail?.qualityAnomalousEvent?.findStaffType == null
        ? null
        : items.firstWhere((element) =>
    num.parse(element.pickId!) ==
        eventDetail?.qualityAnomalousEvent?.findStaffType);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
          var item = items[p1];
          eventDetail?.qualityAnomalousEvent?.findStaffType =
              num.parse(item.pickId!);
          notifyListeners();
        }).show();
  }

  void chooseCausePerson() {
    var items = [
      PickerDataWithIdModel(pickId: '0',pickName: '护士'),
      PickerDataWithIdModel(pickId: '1',pickName: '介护士'),
      PickerDataWithIdModel(pickId: '2',pickName: '长者'),
      PickerDataWithIdModel(pickId: '3',pickName: '家属'),
      PickerDataWithIdModel(pickId: '4',pickName: '其他人员'),
    ];

    var current =
    eventDetail?.qualityAnomalousEvent?.causePersonType == null
        ? null
        : items.firstWhere((element) =>
    num.parse(element.pickId!) ==
        eventDetail?.qualityAnomalousEvent?.causePersonType);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
          var item = items[p1];
          eventDetail?.qualityAnomalousEvent?.causePersonType =
              num.parse(item.pickId!);
          notifyListeners();
        }).show();
  }

  void chooseWrongPattern() {
    var items = [
      PickerDataWithIdModel(pickId: '0',pickName: '遗漏未执行'),
      PickerDataWithIdModel(pickId: '1',pickName: '长者错误'),
      PickerDataWithIdModel(pickId: '2',pickName: '种类错误'),
      PickerDataWithIdModel(pickId: '3',pickName: '剂量错误'),
      PickerDataWithIdModel(pickId: '4',pickName: '途径错误'),
      PickerDataWithIdModel(pickId: '5',pickName: '时间错误'),
      PickerDataWithIdModel(pickId: '6',pickName: '药物使用方法错误'),
      PickerDataWithIdModel(pickId: '7',pickName: '药物品质异常'),
      PickerDataWithIdModel(pickId: '8',pickName: '给药前或中或后监测评估错误'),
      PickerDataWithIdModel(pickId: '9',pickName: '长者顺从性不当'),
      PickerDataWithIdModel(pickId: '10',pickName: '誊写错误'),
      PickerDataWithIdModel(pickId: '11',pickName: '调配错误'),
      PickerDataWithIdModel(pickId: '12',pickName: '键入错误'),
      PickerDataWithIdModel(pickId: '13',pickName: '其他'),
    ];

    var current =
    eventDetail?.qualityAnomalousEvent?.wrongPatternType == null
        ? null
        : items.firstWhere((element) =>
    num.parse(element.pickId!) ==
        eventDetail?.qualityAnomalousEvent?.wrongPatternType);
    DataPickerView(context, items, currentFirstData: current,
        onSubmitListener: (p1, p2, p3) {
          var item = items[p1];
          eventDetail?.qualityAnomalousEvent?.wrongPatternType =
              num.parse(item.pickId!);
          notifyListeners();
        }).show();


  }
}

class MultiChooseSheet extends StatelessWidget {
  String? title;
  List<PickerDataWithIdModel> list;
  List<PickerDataWithIdModel> chooseList = [];
  Function(String ids) submitClick;

  MultiChooseSheet(
      {this.title,
      required this.list,
      String chooseIds = "",
      required this.submitClick}) {
    if (chooseIds.isNotEmpty) {
      var idList = chooseIds.split(",");
      for (var item in list) {
        if (idList.contains(item.pickId)) {
          chooseList.add(item);
        }
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Row(
          children: [
            CommonText('取消', textColor: Colours.gray_99).onTap(() {
              Go().pop();
            }),
            CommonText(title ?? "", textAlign: TextAlign.center, textSize: 18)
                .setWeight(1),
            CommonText('确定', textColor: Colours.app_main).onTap(() {
              Go().pop();
              submitClick(chooseList.isEmpty
                  ? ""
                  : chooseList.map((e) => e.pickId).join(","));
            })
          ],
        ),
        SizedBox(height: 20),
        ListView(
          children: list
              .map((e) {
                return CheckTextItem(
                  title: e.name,
                  onChanged: (value) {
                    if (value) {
                      chooseList.add(e);
                    } else {
                      chooseList.remove(e);
                    }
                  },
                  defaultSelected: chooseList.contains(e),
                );
              })
              .toList()
              .insertWidget(SizedBox(
                height: 10,
              )),
        ).setWeight(1)
      ],
    ).addToContainer(
        decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: 20.radius)),
        padding: EdgeInsets.symmetric(horizontal: 15, vertical: 20));
  }
}
